<?php

namespace App;

use Yolo\Components\Cache\CacheComponent;
use Yolo\Components\EventDispatcher\EventDispatcherComponent;
use Yolo\Components\Middleware\Middlewares\JsonResponseMiddleware;
use Yolo\Components\Scheduler\SchedulerComponent;
use Yolo\Errors\ForbiddenException;
use Yolo\Rpc\Annotations\AppScheme;
use Yolo\Service\AbstractService;
use Yolo\Service\ApplicationContainer;
use Yolo\Service\RpcRequest;
use Yolo\Service\RpcResponse;
use Yolo\Utils\Console;

const SERVICE_NAME = 'TestService';

/**
 * Entry class of the application.
 */
#[AppScheme('service', SERVICE_NAME)]
class App extends AbstractService
{
    public function __construct(
        private readonly ApplicationContainer $container,
    ){}

    public function main(): void
    {
        // You can add your code here before the service start.

        Console::log('The application ID: ' . $this->container->getConfig()->getInstanceId());
    }

    /**
     * Enable the components you need.
     * @return string[]
     */
    public function components(): array
    {
        return [
            CacheComponent::class,
            SchedulerComponent::class,
        ];
    }

    /**
     *  Enable the middlewares you need.
     * @return array
     */
    public function middlewares(): array
    {
        return [
            JsonResponseMiddleware::class,
        ];
    }

    /**
     * Enable the pre-processors you need.
     * @return mixed
     */
    public function preProcessors(): array
    {
        return [
            'getUserByIdPreProcessor' => function (RpcRequest $request, RpcResponse $response): array {

                $body = $request->getBody();
                if ($body['name'] !== 'yolo') {
                    throw new ForbiddenException('The parameter name must be yolo.');
                }

                // Update the request data.
                $request->requestData['body']['name'] = 'new yolo';

                // Must return [$request, $response]
                return [$request, $response];
            },
        ];
    }
}
